<template>
	<div class="mc-popup-select-wrap">
		<div
			class="el-select"
			@click="openDialog"
		>
			<Input
				v-model="innerValue"
				:placeholder="placeholder"
				readonly
				:validate-event="false"
				@mouseenter.native="inputHovering = true"
				@mouseleave.native="inputHovering = false"
			>
				<template #suffix>
					<i
						v-show="!showClose"
						:class="['el-select__caret', 'Input__icon', 'el-icon-arrow-up']"
					/>
					<i
						v-if="showClose"
						class="el-select__caret Input__icon el-icon-circle-close"
						@click="clear"
					/>
				</template>
			</Input>
		</div>
		<template v-if="popupType === 'dialog'">
			<Dialog
				v-if="visible"
				:visible.sync="visible"
				:title="popupTitle"
				:close-on-click-modal="false"
				class="mc-dialog mc-dialog_center"
				lock-scroll
				:append-to-body="true"
				:width="popupWidth"
			>
				<div
					class="flex items-center"
					style="padding-left: 20px"
				>
					<Form
						inline
						@submit.native.prevent
					>
						<FormItem label="关键词">
							<Input
								v-model="listQuery.keyword"
								:placeholder="t('请输入') + t('关键词') + t('查询')"
								clearable
								class="w-full"
								@keyup.enter.native="search()"
							/>
						</FormItem>
						<FormItem>
							<Button
								type="primary"
								icon="el-icon-search"
								@click="search()"
							>
								{{t("查询")}}
							</Button>
							<Button
								icon="el-icon-refresh-right"
								@click="reset()"
							>
								{{t("重置")}}
							</Button>
						</FormItem>
						<FormItem>
							<Tooltip
								effect="dark"
								:content="t('刷新')"
								placement="top"
							>
								<Link
									icon="icon-ym icon-ym-Refresh mc-common-head-icon"
									:underline="false"
									@click="initData()"
								/>
							</Tooltip>
						</FormItem>
					</Form>
				</div>
				<McTable
					v-loading="listLoading"
					:data="list"
					:border="false"
					highlight-current-row
					:has-n-o="false"
					@row-click="rowClick"
				>
					<TableColumn
						v-if="columnOptions.length"
						width="35"
					>
						<template #default="scope">
							<Radio
								v-model="checked"
								:label="scope.row[propsValue]"
							>
&nbsp;
							</Radio>
						</template>
					</TableColumn>
					<TableColumn
						v-if="columnOptions.length"
						type="index"
						width="50"
						label="序号"
						align="center"
					/>
					<TableColumn
						v-for="(item, i) in columnOptions"
						:key="i"
						:prop="item.value"
						:label="item.label"
					/>
				</McTable>
				<pagination
					v-if="hasPage"
					:page="listQuery.currentPage"
					:limit="listQuery.pageSize"
					:total="total"
					@pagination="initData"
				/>
				<template #footer>
					<span
						class="dialog-footer"
					>
						<Button
							size="small"
							@click="visible = false"
						>{{t("取消")}}</Button>
						<Button
							type="primary"
							size="small"
							@click="select()"
						>{{t("确定")}}
						</Button>
					</span>
				</template>
			</Dialog>
		</template>
		<template v-if="popupType === 'drawer'">
			<Drawer
				ref="drawer"
				:visible.sync="visible"
				:title="popupTitle"
				:wrapper-closable="false"
				:size="popupWidth"
				:append-to-body="true"
				class="mc-common-drawer"
			>
				<div class="mc-flex-main">
					<Row
						class="mc-common-search-box"
						:gutter="16"
					>
						<Form @submit.native.prevent>
							<Col :span="10">
								<FormItem label="关键词">
									<Input
										v-model="listQuery.keyword"
										:placeholder="t('请输入') + t('关键词') + t('查询')"
										clearable
										class="search-input"
										@keyup.enter.native="search()"
									/>
								</FormItem>
							</Col>
							<Col :span="8">
								<FormItem>
									<Button
										type="primary"
										icon="el-icon-search"
										@click="search()"
									>
										{{t("查询")}}
									</Button>
									<Button
										icon="el-icon-refresh-right"
										@click="reset()"
									>
										{{t("重置")}}
									</Button>
								</FormItem>
							</Col>
						</Form>
						<div class="mc-common-search-box-right">
							<Tooltip
								effect="dark"
								:content="t('刷新')"
								placement="top"
							>
								<Link
									icon="icon-ym icon-ym-Refresh mc-common-head-icon"
									:underline="false"
									@click="initData()"
								/>
							</Tooltip>
						</div>
					</Row>
					<McTable
						v-loading="listLoading"
						:data="list"
						:border="false"
						highlight-current-row
						:has-n-o="false"
						@row-click="rowClick"
					>
						<TableColumn
							v-if="columnOptions.length"
							width="35"
						>
							<template #default="scope">
								<Radio
									v-model="checked"
									:label="scope.row[propsValue]"
								>
&nbsp;
								</Radio>
							</template>
						</TableColumn>
						<TableColumn
							v-if="columnOptions.length"
							type="index"
							width="50"
							label="序号"
							align="center"
						/>
						<TableColumn
							v-for="(item, i) in columnOptions"
							:key="i"
							:prop="item.value"
							:label="item.label"
						/>
					</McTable>
					<pagination
						v-if="hasPage"
						:page="listQuery.currentPage"
						:limit="listQuery.pageSize"
						:total="total"
						@pagination="initData"
					/>
					<div class="drawer-footer">
						<Button
							size="small"
							@click="visible = false"
						>
							{{t("取消")}}
						</Button>
						<Button
							type="primary"
							size="small"
							@click="select()"
						>
							{{t("确定")}}
						</Button>
					</div>
				</div>
			</Drawer>
		</template>
	</div>
</template>

<script>
import McTable from '../table';
import {getScriptFunc, t} from '../../utils/index.js';
import {Input, Dialog, Form, FormItem, Radio, TableColumn, Button, Row, Col, Tooltip, Drawer} from 'element-ui';
export default {
	name:'McPopupSelect',
	components:{
		McTable,
		Input, Dialog, Form, FormItem, Radio, TableColumn, Button, Row, Col, Tooltip, Drawer,
	},
	model:{
		prop:'value',
		event:'input',
	},
	props:{
		value:{
			default:'',
			type:String,
		},
		rowIndex:{
			default:null,
			type:Number,
		},
		formData:{
			type:Object,
		},
		templateJson:{
			type:Array,
			default: () => [],
		},
		interfaceId:{
			type:String,
			default:'',
		},
		placeholder:{
			type:String,
			default:'请选择',
		},
		propsValue:{
			type:String,
			default:'id',
		},
		relationField:{
			type:String,
			default:'fullName',
		},
		popupType:{
			type:String,
			default:'dialog',
		},
		popupTitle:{
			type:String,
			default:'选择数据',
		},
		popupWidth:{
			type:String,
			default:'800px',
		},
		field:{
			type:String,
			default:'',
		},
		columnOptions:{
			type:Array,
			default: () => [],
		},
		hasPage:{
			type:Boolean,
			default:false,
		},
		pageSize:{
			type:Number,
			default:20,
		},
		multiple:{
			type:Boolean,
			default:false,
		},
		disabled:{
			type:Boolean,
			default:false,
		},
		clearable:{
			type:Boolean,
			default:true,
		},
	},
	data(){
		return {
			t,
			list:[],
			innerValue:'',
			listQuery:{
				keyword:'',
				currentPage:1,
				pageSize:20,
			},
			total:0,
			checked:'',
			checkedTxt:'',
			checkedRow:{},
			listLoading:false,
			visible:false,
			inputHovering:false,
		};
	},
	computed:{
		showClose(){
			const hasValue = this.multiple
				? Array.isArray(this.value) && this.value.length > 0
				: this.value !== undefined && this.value !== null && this.value !== '';
			const criteria = this.clearable && !this.disabled && this.inputHovering && hasValue;
			return criteria;
		},
		propsLabel(){
			return this.columnOptions[0].value;
		},
	},
	watch:{
		value(val){
			this.setDefault();
		},
	},
	created(){
		this.listQuery.pageSize = this.hasPage ? this.pageSize : 100000;
		this.setDefault();
	},
	methods:{
		initData(){
			if(!this.interfaceId) return;
			this.listLoading = true;
			const paramList = this.getParamList();
			const columnOptions = this.columnOptions.map((o) => o.value);
			const query = {
				...this.listQuery,
				interfaceId:this.interfaceId,
				propsValue:this.propsValue,
				relationField:this.relationField,
				columnOptions:columnOptions.join(','),
				paramList,
			};
			this.getDataInterfaceDataSelect(this.interfaceId, query)
				.then((res) => {
					this.list = res.data.list;
					this.total = res.data.pagination.total;
					this.listLoading = false;
				})
				.catch(() => {
					this.listLoading = false;
				});
		},
		getParamList(){
			const templateJson = this.templateJson;
			if(!this.formData) return templateJson;
			for(let i = 0; i < templateJson.length; i++){
				if(templateJson[i].relationField){
					if(templateJson[i].relationField.includes('-')){
						const tableVModel = templateJson[i].relationField.split('-')[0];
						const childVModel = templateJson[i].relationField.split('-')[1];
						templateJson[i].defaultValue
                            = (this.formData[tableVModel]
                            	&& this.formData[tableVModel][this.rowIndex]
                            	&& this.formData[tableVModel][this.rowIndex][childVModel])
                            	|| '';
					}else{
						templateJson[i].defaultValue
                            = this.formData[templateJson[i].relationField] || '';
					}
				}
			}
			return templateJson;
		},
		interfaceDataHandler(data){
			if(!data.dataProcessing) return data.list;
			const dataHandler = getScriptFunc.call(this, data.dataProcessing);
			if(!dataHandler) return data.list;
			return dataHandler(data.list);
		},
		search(){
			this.initData();
			this.listQuery.currentPage = 1;
			this.listQuery.pageSize = this.hasPage ? this.pageSize : 10000;
		},
		reset(){
			this.listQuery.keyword = '';
			this.listQuery.currentPage = 1;
			this.listQuery.pageSize = this.hasPage ? this.pageSize : 10000;
			this.initData();
		},
		openDialog(){
			if(this.disabled) return;
			this.checked = this.value;
			this.visible = true;
			this.reset();
		},
		clear(event){
			this.checked = '';
			this.innerValue = '';
			this.checkedRow = {};
			this.$emit('input', this.checked);
			this.$emit('change', this.checked, this.checkedRow);
			event.stopPropagation();
		},
		select(){
			if(!this.checked) return;
			this.innerValue = this.checkedTxt;
			this.$emit('input', this.checked);
			this.$emit('change', this.checked, this.checkedRow);
			this.visible = false;
		},
		rowClick(row){
			this.checked = row[this.propsValue];
			this.checkedTxt = row[this.relationField];
			this.checkedRow = row;
		},
		setDefault(){
			if(this.value){
				if(!this.interfaceId) return;
				const paramList = this.getParamList();
				const query = {
					ids:[this.value],
					interfaceId:this.interfaceId,
					propsValue:this.propsValue,
					relationField:this.relationField,
					paramList,
				};
				this.getDataInterfaceDataInfoByIds(this.interfaceId, query).then((res) => {
					const data = res.data && res.data.length ? res.data[0] : {};
					this.innerValue = data[this.relationField];
					if(!this.field) return;
					const relationData = this.$store.state.generator.relationData;
					this.$set(relationData, this.field, data);
					this.$eventBus.$emit('popupAttrEventBus', relationData, this.field);
					this.$store.commit('generator/UPDATE_RELATION_DATA', relationData);
				});
			}else{
				this.innerValue = '';
				if(!this.field) return;
				const relationData = this.$store.state.generator.relationData;
				this.$set(relationData, this.field, {});
				this.$eventBus.$emit('popupAttrEventBus', relationData, this.field);
				this.$store.commit('generator/UPDATE_RELATION_DATA', relationData);
			}
		},
		getDataInterfaceDataSelect(id, data){
			//return this.$httpService({
			//	url:`/api/system/DataInterface/${id}/Action/List`,
			//	method:'post',
			//	data,
			//});
			return new Promise((resolve)=>resolve('接口未迁移'));
		},
		getDataInterfaceDataInfoByIds(id, data){
			//return this.$httpService({
			//	url:`/api/system/DataInterface/${id}/Action/InfoByIds`,
			//	method:'POST',
			//	data,
			//});
			return new Promise((resolve)=>resolve('接口未迁移'));
		},
	},
};
</script>
<style lang="scss" scoped>
::v-deep .el-dialog__body {
    height: 70vh;
    padding: 0 0 10px !important;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    .mc-common-search-box {
        margin-bottom: 0;
        .mc-common-search-box-right {
            padding: 10px 10px 0 0;
        }
    }
}
</style>